package imdservice.thread;

import imdservice.net.SocketClientManager;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
    * 指令处理线程
    * @Create by Charlie
    * @Date: 11:17 2017/7/12
*/
public class ServerThread implements Runnable{
    private String mIp;
    private Socket mSocket;

    public ServerThread(String mIp) {
        this.mIp = mIp;
        try {
            mSocket = SocketClientManager.getSocket(mIp,8624);
            System.out.println("Socket Service: " + "移动服务器");
            System.out.println("Socket Address: " + mSocket.getInetAddress());
            System.out.println("Socket Port: " + mSocket.getLocalPort());
            System.out.println("Socket Service: " + "本地客户端");
            System.out.println("Socket Port: " + mSocket.getLocalSocketAddress());
            System.out.println("Socket LockPort: " + mSocket.getLocalPort());
            System.out.println("Socket KeepAlive: " + mSocket.getKeepAlive());
            System.out.println("Socket Channel: " + mSocket.getChannel());
            System.out.println("等待指令......");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            //TODO: 获取套接读写流
            OutputStream os = mSocket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            //TODO: 输入流
            InputStream is = mSocket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            //TODO: 读写操作
            String s = "install";
            pw.write(s);
            pw.flush();
            mSocket.shutdownOutput();
            //TODO: 接受服务器响应
            String reply = null;
            while (!((reply = br.readLine()) == null)){
                System.out.println("服务器回传的消息：" + reply);
            }
            //TODO: 关闭资源
            br.close();
            is.close();
            pw.close();
            os.close();
            mSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
